<template>
  <div>
    <el-breadcrumb class="app-breadcrumb" separator="/">
      <transition-group name="breadcrumb">
        <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
          <!-- 判断是不是最后一项 -->
          <span
            v-if="
              item.redirect === 'noRedirect' || index === levelList.length - 1
            "
            class="no-redirect"
            >{{ item.meta.title }}</span
          >
          <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>
  </div>
</template>
<script>
export default {
  name: "BreadCrumb",
  data() {
    return {
      levelList: [],
    };
  },
  created() {
    this.getBreadCrumb();
  },
  watch: {
    $route() {
      this.getBreadCrumb();
    },
  },
  methods: {
    // 面包屑的处理逻辑
    getBreadCrumb() {
      // 获取嵌套的路由
      let matched = this.$route.matched.filter(
        (item) => item.meta && item.meta.title && !item.meta.breadcrumbHidden
      );
      let first = matched[0];
      // 当前不是首页，将首页添加到面包屑里面
      if (!this.isHome(first)) {
        matched = [{ path: "/home", meta: { title: "首页" } }].concat(matched);
      }
      this.levelList = matched;
    },
    // 判断当前的路由是否为首页
    isHome(route) {
      return route.meta.title.trim() === "首页";
    },
    // 面包屑的跳转方法
    handleLink(item) {
      const { redirect, path } = item;
      if (redirect) {
        this.$router.push(redirect);
        return;
      }
      this.$router.push({ path: path });
    },
  },
};
</script>
<style lang="less" scoped>
.app-breadcrumb .sa-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
